/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lvyh.lightframe.transaction.core.ext;


import com.lvyh.lightframe.transaction.common.exception.TransactionRuntimeException;
import com.lvyh.lightframe.transaction.common.util.ClassUtils;

/**
 * Extension interface implementation class
 */
public class ExtensionClass<T> {

    /**
     * Extension interface implementation class name
     */
    protected final Class<? extends T> clazz;
    /**
     * Extended alias
     */
    protected final String alias;

    public ExtensionClass(Class<? extends T> clazz, String alias) {
        this.clazz = clazz;
        this.alias = alias;
    }

    /**
     * Get the server instance object. If it is a singleton, return the singleton object.
     * If it is not, return the newly created instance object
     *
     * @return Extension point object instance
     */
    public T getExtInstance() {
        return getExtInstance(null, null);
    }

    /**
     * Get the server instance object. If it is a singleton, return the singleton object.
     * If it is not, return the newly created instance object
     *
     * @param argTypes Constructor parameter type
     * @param args     Constructor parameter value
     * @return ext instance
     */
    public T getExtInstance(Class[] argTypes, Object[] args) {
        if (clazz != null) {
            try {
                return ClassUtils.newInstanceWithArgs(clazz, argTypes, args);
            } catch (Exception e) {
                throw new TransactionRuntimeException("create ext instance error,", e);
            }
        }
        throw new TransactionRuntimeException("extension class can not be null.");
    }

    public String getAlias() {
        return alias;
    }


    public Class<? extends T> getClazz() {
        return clazz;
    }


    @Override
    public String toString() {
        return "ExtensionClass{" +
                "clazz=" + clazz +
                ", alias='" + alias + '\'' +
                '}';
    }
}
